<template>
  <div class="favorites-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>我的收藏</h2>
      <div class="header-actions">
        <el-button-group>

         <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
            <el-icon>
              <List />
            </el-icon>
          </el-button>
          <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="viewMode = 'grid'">
            <el-icon>
              <Grid />
            </el-icon>
          </el-button>
         
        </el-button-group>
        <el-button type="danger" plain @click="handleBatchDelete" :disabled="!selectedItems.length">
          <el-icon>
            <Delete />
          </el-icon>
          删除选中
        </el-button>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="favorites-content">
      <!-- 网格视图 -->
      <template v-if="viewMode === 'grid'">
        <el-row :gutter="20">
          <el-col v-for="item in favorites" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6">
            <el-card class="product-card" :body-style="{ padding: '0px' }">
              <div class="card-checkbox">
                <el-checkbox v-model="selectedItems" :label="item.id" />
              </div>
              <el-image :src="item.mainImage" class="product-image" fit="cover" @click="viewProduct(item)">
                <template #error>
                  <div class="image-placeholder">
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
              <div class="product-info">
                <h3 class="product-name" @click="viewProduct(item)">{{ item.name }}</h3>
                <div class="product-price">
                  <span class="price">¥{{ item.price }}</span>
                  <span class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice }}</span>
                </div>
                <div class="product-actions">
                  <el-button type="primary" size="small" @click="addToCart(item)">
                    <el-icon>
                      <ShoppingCart />
                    </el-icon>
                    加入购物车
                  </el-button>
                  <el-button type="danger" size="small" @click="removeFromFavorites(item)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>

      <!-- 列表视图 -->
      <template v-else>
        <el-table :data="favorites" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="商品信息" min-width="400">
            <template #default="{ row }">
              <div class="product-info-row">
                <el-image :src="row.mainImage" class="list-image" @click="viewProduct(row)">
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="product-detail">
                  <h3 class="product-name" @click="viewProduct(row)">{{ row.name }}</h3>
                  <div class="product-specs">{{ row.specs }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="150" align="center">
            <template #default="{ row }">
              <div class="price-column">
                <span class="price">¥{{ row.price }}</span>
                <span class="original-price" v-if="row.originalPrice">¥{{ row.originalPrice }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="收藏时间" width="180" align="center">
            <template #default="{ row }">
              {{ row.favoriteTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="addToCart(row)">
                <el-icon>
                  <ShoppingCart />
                </el-icon>
                加入购物车
              </el-button>
              <el-button type="danger" size="small" @click="removeFromFavorites(row)">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination :current-page="currentPage" :page-size="pageSize" :total="total" :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!favorites.length" description="暂无收藏商品">
      <el-button type="primary" @click="goToProducts">去逛逛</el-button>
    </el-empty>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Grid,
  List,
  Delete,
  Picture,
  ShoppingCart
} from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()
const viewMode = ref('list')
const selectedItems = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(100)

// 收藏数据
const favorites = ref([])

// 获取收藏列表
const fetchFavorites = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      return
    }

    const res = await request.get(`/favorites/user/${userInfo.id}`, {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })

    if (res && res.code === 200 && res.data) {
      favorites.value = res.data.content || []
      total.value = res.data.totalElements || 0
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  }
}

// 查看商品详情
const viewProduct = (product) => {
  router.push({
    path: `/home/product/${product.productId || product.id}`
  })
}

// 加入购物车
const addToCart = async (product) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

    if (!userInfo.id) {
      // 如果未登录，使用localStorage
      const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]')
      const existingItem = cartItems.find(item => item.id === (product.productId || product.id))

      if (existingItem) {
        existingItem.quantity += 1
      } else {
        cartItems.push({
          id: product.productId || product.id,
          name: product.name,
          price: product.price,
          mainImage: product.mainImage,
          quantity: 1
        })
      }

      localStorage.setItem('cartItems', JSON.stringify(cartItems))
      window.emitter?.emit('cart-updated')
      ElMessage.success('已加入购物车')
      return
    }

    // 如果已登录，调用后端API
    const cartData = {
      userId: userInfo.id,
      productId: product.productId || product.id,
      quantity: 1
    }

    await request.post('/cart', cartData)
    window.emitter?.emit('cart-updated')
    ElMessage.success('已加入购物车')
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 从收藏夹移除
const removeFromFavorites = async (product) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.delete(`/favorites/${product.id}`)
    if (res && res.code === 200) {
      ElMessage.success('已取消收藏')
      fetchFavorites() // 重新获取列表
    } else {
      ElMessage.error('取消收藏失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('取消收藏失败:', error)
      ElMessage.error('取消收藏失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedItems.value.length) return

  try {
    await ElMessageBox.confirm(`确定要取消收藏这${selectedItems.value.length}件商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.delete('/favorites/batch', {
      data: selectedItems.value
    })

    if (res && res.code === 200) {
      ElMessage.success('已取消收藏')
      selectedItems.value = []
      fetchFavorites() // 重新获取列表
    } else {
      ElMessage.error('取消收藏失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('批量取消收藏失败:', error)
      ElMessage.error('取消收藏失败')
    }
  }
}

// 列表视图选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection.map(item => item.id)
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchFavorites()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFavorites()
}

// 跳转到商品列表
const goToProducts = () => {
  router.push('/home/products')
}

// 页面初始化
onMounted(() => {
  fetchFavorites()
})
</script>

<style scoped>
.favorites-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.favorites-content {
  margin-bottom: 20px;
}

.product-card {
  position: relative;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
}

.product-image {
  width: 100%;
  height: 200px;
  cursor: pointer;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  cursor: pointer;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-name:hover {
  color: #409EFF;
}

.product-price {
  margin-bottom: 15px;
}

.price {
  color: #F56C6C;
  font-size: 20px;
  font-weight: bold;
}

.original-price {
  color: #909399;
  font-size: 14px;
  text-decoration: line-through;
  margin-left: 5px;
}

.product-actions {
  display: flex;
  gap: 10px;
}

.product-info-row {
  display: flex;
  align-items: center;
  gap: 15px;
}

.list-image {
  width: 100px;
  height: 100px;
  cursor: pointer;
}

.product-detail {
  flex: 1;
}

.product-specs {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
}

.price-column {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>